package com.qiji.video.config;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@EnableSwagger2
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.qiji.video.web"))
                .build()
                .securitySchemes(security())
                .securityContexts(securityContexts());
    }
    public ApiInfo apiInfo(){
        Contact contact=new Contact("视频播放网站","","");
        return new ApiInfo("视频播放网站",
                "Api Documentation",
                "1.0",
                "urn:tos",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());
    }
    private List<ApiKey> security(){
        return Collections.singletonList(
                new ApiKey("token","token","header"));
    }
    /**
     * 设置认证规则
     */
    private List<SecurityContext> securityContexts(){
        List<String> antPaths = new ArrayList<>(Arrays.asList("/auth/**"));
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(antPathsCondition(antPaths))
                        .build()
        );
    }

    /**
     * 返回认证路径
     */
    private Predicate<String> antPathsCondition(List<String> antPaths){
        List<Predicate<String>> list = new ArrayList<>();
        antPaths.forEach(path->list.add(PathSelectors.ant(path)));
        return Predicates.or(list);
    }

    /**
     * 设置认证的范围，以及认证的字段名称
     */
    private List<SecurityReference> defaultAuth(){
        AuthorizationScope authorizationScope = new AuthorizationScope("global","accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Collections.singletonList(
                new SecurityReference("token", authorizationScopes)
        );
    }

}
